<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator.prototype.return()</title>
</head>
<body>
    <h1>Generator.prototype.return()</h1>
    <h2>返回给定的值，并且终结遍历Generator函数</h2>

    <script>
        // 基本用法
        function* gen() {
            yield 1;
            yield 2;
            yield 3;
        }

        const g = gen();
        console.log(g.next());        // { value: 1, done: false }
        console.log(g.return('foo')); // { value: "foo", done: true }
        console.log(g.next());        // { value: undefined, done: true }

        // 如果return()方法调用时，不提供参数
        function* gen2() {
            yield 1;
            yield 2;
        }
        const g2 = gen2();
        console.log(g2.next());      // { value: 1, done: false }
        console.log(g2.return());    // { value: undefined, done: true }

        // try...finally与return()
        function* numbers() {
            yield 1;
            try {
                yield 2;
                yield 3;
            } finally {
                yield 4;
                yield 5;
            }
            yield 6;
        }

        const g3 = numbers();
        console.log(g3.next());     // { value: 1, done: false }
        console.log(g3.next());     // { value: 2, done: false }
        console.log(g3.return(7));  // { value: 4, done: false }
        console.log(g3.next());     // { value: 5, done: false }
        console.log(g3.next());     // { value: 7, done: true }
    </script>
</body>
</html> 